﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMessageBox>
#include "common.h"
#include "Logger.h"
#include "syscfg.h"
#include "computerwindget.h"
#include "computermanager.h"
#include "sendemailtask.h"
#include "getserverfromdb.h"
#include "qfiledialog.h"
#include "TcpConnectHandler.h"
#include "appupdatereq.h"
#include "commonresp.h"

#define COMPUTER_DISPLAY_COL 5 //5个一排


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(&gComputerManager, SIGNAL(computersUpdated()), this, SLOT(on_computersUpdated()));
    connect(&gComputerManager, SIGNAL(offlineAndALarmCountUpdate(int,int,int)), this, SLOT(on_offlineAndALarmCountUpdate(int,int,int)));
    connect(ui->offlineRadioButton, SIGNAL(clicked(bool)), this, SLOT(on_computerQueryConditionsChanged()));
    connect(ui->unreadAlarmRadioButton, SIGNAL(clicked(bool)), this, SLOT(on_computerQueryConditionsChanged()));
    connect(&gComputerManager, SIGNAL(computersUpdated()), this, SLOT(on_needUpdateAppsComputerChanged()));

    init();

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::checkAutoStart()
{
    bool autoStart = isSelfAutoStart();
    if(!autoStart)
    {

        if(QMessageBox::Yes == QMessageBox::information(this, "提示", "是否开起开机自启动",QMessageBox::Yes | QMessageBox::No))
        {
            if (f_success == setSelfAutoStart(true))
            {
                ui->autoStartRadioButton->setChecked(true);
            }
            else
            {
                ui->autoStartRadioButton->setChecked(false);
                QMessageBox::warning(this, "提示", "设置开机自启动失败,请确认当前程序是否有权限访问:C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp\\");
            }

        }
        else
        {
           ui->autoStartRadioButton->setChecked(false);
        }
    }
    else
    {
        ui->autoStartRadioButton->setChecked(true);
    }
}

void MainWindow::init()
{
    checkAutoStart();

    gComputerManager.start();

    ui->listenSocketLineEdite->setText(int2QStr(LISTEN_PORT));
    ui->clientListenSocketLineEdite->setText(int2QStr(CLIENT_LISTEN_PORT));
    ui->sendEmailIntervalSecondsLineEdit->setText(int2QStr(SEND_EMAIL_INTERVAL_SECONDS));
    ui->sendEmailTosLineEdit->setText(SEND_EMAIL_TOS);
    ui->sendEmailFromLineEdite->setText(SMTP_FROM_MAIL);
    ui->smtpAddressLineEdit->setText(SMTP_HOST);
    ui->smtpPortLineEdit->setText(int2QStr(SMTP_PORT));
    ui->smtpUserNameLineEdit->setText(SMTP_USER_NAME);
    ui->smtpPasswdLineEdit->setText(SMTP_PASSWD);

    for (int i = 0; i < COMPUTER_DISPLAY_COL; i++)
    {
        ui->computerGridLayOut->setColumnStretch(i, 40);
        ui->updateAppsComputerGridLayOut->setColumnStretch(i, 40);
    }


    for (int i = 0; i < 16; i++)
    {
        ui->computerGridLayOut->setRowStretch(i, 40);
        ui->updateAppsComputerGridLayOut->setRowStretch(i, 40);
    }

    QString apps = IMPORTANT_APPS;
    QStringList appList = apps.split(",");
    ui->appNamesComboBox->addItems(appList);

    ui->offlineRadioButton->setAutoExclusive(false);
    ui->unreadAlarmRadioButton->setAutoExclusive(false);
}

void MainWindow::on_autoStartRadioButton_clicked(bool autoStart)
{
    LOG_INFO("change autoStart to:%s",boolToYesOrNo(autoStart));
    if(autoStart == false &&  QMessageBox::No == QMessageBox::warning(this, "提示", "确认取消开机启动吗?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes))
    {
        ui->autoStartRadioButton->setChecked(true);
        return;
    }
    if(f_success == setSelfAutoStart(autoStart))
    {
        ui->autoStartRadioButton->setChecked(autoStart);
    }
    else
    {
        QMessageBox::warning(this, "警告", "修改开机启动失败,请确认当前程序是否有管理员权限");
        ui->autoStartRadioButton->setChecked(!autoStart);
    }
}

void MainWindow::on_listenSocketLineEdite_editingFinished()
{
    SAVE_LISTEN_PORT(ui->listenSocketLineEdite->text().toInt());
}

void MainWindow::on_clientListenSocketLineEdite_editingFinished()
{
    SAVE_CLIENT_LISTEN_PORT(ui->clientListenSocketLineEdite->text().toInt());
}

void MainWindow::on_addComputerButton_clicked(bool checked)
{
    ComputerWindget * win = new ComputerWindget(this);
    win->setModal(false);
    win->prepareCreate();
    win->show();
}

void MainWindow::on_computersUpdated()
{


    QList<Computer> computers = gComputerManager.getCopyOfComputers(ui->offlineRadioButton->isChecked(), ui->unreadAlarmRadioButton->isChecked());
    if(computers.size() < computerInfoWidgets.size())
    {
        for (int i = 0; i < computerInfoWidgets.size() - computers.size(); i ++)
        {
            SafeDeleteObj(computerInfoWidgets.front());
            computerInfoWidgets.pop_front();
        }
    }
    else if (computers.size() > computerInfoWidgets.size())
    {
        int i = computers.size() - computerInfoWidgets.size();
        for (int j = 0; j < i; j++)
        {
            computerInfoWidgets.push_back(new ComputerInfoWidget(computers.front()));
        }
    }


    int i= 0;

    list<ComputerInfoWidget *>::iterator iter = computerInfoWidgets.begin();
    foreach (Computer computer, computers) {
        (*iter)->setComputer(computer);
        ui->computerGridLayOut->addWidget(*iter, i/COMPUTER_DISPLAY_COL, i%COMPUTER_DISPLAY_COL);
        iter++;
        i++;
    }


}

void MainWindow::on_needUpdateAppsComputerChanged()
{
    QString appName(ui->appNamesComboBox->currentText());
    QList<Computer> computers = gComputerManager.getCopyOfOnlineComputers(appName);

    if(computers.size() < updateAppsComputerInfoWidgets.size())
    {
        for (int i = 0; i < updateAppsComputerInfoWidgets.size() - computers.size(); i ++)
        {
            SafeDeleteObj(updateAppsComputerInfoWidgets.front());
            updateAppsComputerInfoWidgets.pop_front();
        }
    }
    else if (computers.size() > updateAppsComputerInfoWidgets.size())
    {
        int i = computers.size() - updateAppsComputerInfoWidgets.size();
        for (int j = 0; j < i; j++)
        {
            updateAppsComputerInfoWidgets.push_back(new NeedUpdateAppComputerWidget(computers.front()));
        }
    }


    int i= 0;

    list<NeedUpdateAppComputerWidget *>::iterator iter = updateAppsComputerInfoWidgets.begin();
    foreach (Computer computer, computers) {
        (*iter)->setComputer(computer);
        ui->updateAppsComputerGridLayOut->addWidget(*iter, i/COMPUTER_DISPLAY_COL, i%COMPUTER_DISPLAY_COL);
        iter++;
        i++;
    }
}

void MainWindow::on_computerQueryConditionsChanged()
{
    SafeClearListAndDelEle(ComputerInfoWidget, computerInfoWidgets);
    on_computersUpdated();
}


void MainWindow::on_offlineAndALarmCountUpdate(int offLineCount, int allComputerCount, int unreadAlarmCount)
{
    ui->computersConnectInfoLabel->setText(int2QStr(allComputerCount - offLineCount) + "/" + int2QStr(allComputerCount) + "台服务器已连接");
    ui->computerUnreadALarmCountLabel->setText("有" + int2QStr(unreadAlarmCount) + "条未读异常告警");
}


void MainWindow::on_sendEmailIntervalSecondsLineEdit_editingFinished()
{
    SAVE_SEND_EMAIL_INTERVAL_SECONDS(ui->sendEmailIntervalSecondsLineEdit->text().toInt());
//    gSendEmailTask.stopAndWaitThreadQuit();
//    gSendEmailTask.start();
}

void MainWindow::on_sendEmailTosLineEdit_editingFinished()
{
    SAVE_SEND_EMAIL_TOS(ui->sendEmailTosLineEdit->text());
//    gSendEmailTask.stopAndWaitThreadQuit();;
//    gSendEmailTask.start();
}

void MainWindow::on_smtpAddressLineEdit_editingFinished()
{
    SAVE_SMTP_HOST(ui->smtpAddressLineEdit->text());
//    gSendEmailTask.stopAndWaitThreadQuit();;
//    gSendEmailTask.start();
}





void MainWindow::on_smtpPortLineEdit_editingFinished()
{
    SAVE_SMTP_PORT(ui->smtpPortLineEdit->text().toInt());
//    gSendEmailTask.stopAndWaitThreadQuit();;
//    gSendEmailTask.start();
}

void MainWindow::on_sendEmailFromLineEdite_editingFinished()
{
    SAVE_SMTP_FROM_MAIL(ui->sendEmailFromLineEdite->text());
}

void MainWindow::on_smtpUserNameLineEdit_editingFinished()
{
    SAVE_SMTP_USER_NAME(ui->smtpUserNameLineEdit->text());
}



void MainWindow::on_smtpPasswdLineEdit_editingFinished()
{
    SAVE_SMTP_PASSWD(ui->smtpPasswdLineEdit->text());
}

void MainWindow::on_getFromDBButton_clicked(bool checked)
{
    GETSERVERFROMDB * win = new GETSERVERFROMDB(this);
    win->setModal(false);
    win->show();
}

void MainWindow::on_appNamesComboBox_currentIndexChanged(const QString &arg1)
{
    SafeClearListAndDelEle(NeedUpdateAppComputerWidget, updateAppsComputerInfoWidgets);
    on_needUpdateAppsComputerChanged();
}

void MainWindow::on_pushButton_clicked()
{  
    QString filePath = QFileDialog::getOpenFileName(this,tr("pick file"),NULL);
    QFileInfo file(filePath);
    SString fileName = file.fileName().toStdString();
    if(!filePath.isEmpty())
    {
        QMessageBox::StandardButton rb = QMessageBox::question(NULL, "question", "Ready to update?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        if(rb == QMessageBox::Yes)
        {
            SString app = ui->appNamesComboBox->currentText().toStdString();
            byte *buffer = NULL;
            long buffLen = 0;
            if(readDataFromFile(filePath, buffer, buffLen) == f_success)
            {
                list<NeedUpdateAppComputerWidget *>::iterator iter;
                for(iter = updateAppsComputerInfoWidgets.begin(); iter != updateAppsComputerInfoWidgets.end(); iter++)
                {

                    TcpConnectHandler * connect = TcpConnectHandler::connect(((*iter)->computer).ip.toStdString(), CLIENT_LISTEN_PORT);
                    if(connect)
                    {
                        AppUpdateReq *updateReq = new AppUpdateReq(app, fileName, buffer, buffLen);

                        if(f_success == connect->sendMsg((BaseMsg*)updateReq))
                        {
                            CommonResp *res = (CommonResp *)connect->readMsg();
                            if(res)
                            {
                                if(res->code == CommonRespResult_success)
                                {
                                    LOG_INFO("read one common response msg with success code, send one update request success");
                                }
                            }
                            else
                            {
                                LOG_ERROR("try to read res failed, may net error?");
                            }

                            SafeDeleteObj(res);
                        }
                        else
                        {
                            LOG_ERROR("try to send out update req to client failed");
                        }

                        SafeDeleteObj(updateReq);
                        SafeDeleteObj(connect);
                    }
                    else
                    {
                        LOG_ERROR("try to connect to client failed");
                    }
                }

            }
        }


    }
}
